import { db } from "@/service/db";

export class ScriptResource {
    public id: string;
    constructor(id: string) {
        this.id = id;
    }

    getCaches() {
        return db.resources.filter(p => {
            return p.sid == this.id && p.type === 'cache';
        }).toArray();
    }

    async getRuntime(resources: ScriptResourceInfo[]) {
        const runtimeData = {
            resources,
            caches: await this.getCaches(),
        }

        return `window.DogruntimeData = ${JSON.stringify(runtimeData)};`
    }

    async setCache(k: string, v: any) {
        const objs = await db.resources.filter(res => res.key === k && res.sid === this.id).toArray()
        if (objs[0]) {
            await db.resources.update(objs[0].id, {
                data: v
            })
        } else {
            await db.resources.add({
                sid: this.id,
                key: k,
                data: v,
                resourceType: 'text/plain',
                type: 'cache'
            })
        }
    }

    async removeCache(k: string) {
        await db.resources.filter(c => {
            return c.sid === this.id && c.key === k
        }).delete()
    }

    async remvoeAllCache() {
        await db.resources.filter(c => {
            return c.sid === this.id
        }).delete()
    }
}